﻿using System;
using System.Collections.Generic;
using System.IO;
using Foothill.Common;
using Foothill.Common.Logging;
using Foothill.DataAccess.Interface;

namespace Foothill.Service.UploadPhoto
{
    public class UploadPhotoService : System.Web.UI.Page, IUploadPhotoService
    {
        private IPhotoRepo _photoRepo;

        public UploadPhotoService(IPhotoRepo photoRepo)
        {
            _photoRepo = photoRepo;
        }

        public void InsertPhotos(IList<Model.UploadPhoto> photoList, int adId, AdType adType)
        {
            foreach (Model.UploadPhoto photo in photoList)
            {
                photo.AdId = adId;
                photo.AdTypeId = (int)adType;
            }

            _photoRepo.InsertPhotos(photoList);
        }

        public IList<Model.UploadPhoto> GetForSaleAdUploadedPhotos(int postId)
        {
            return _photoRepo.GetForSaleAdUploadedPhotos(postId);
        }

        public void DeletePhotoAndThumbnail(string photoFileName, string thumbnailFileName)
        {
            string pathOnServer = GetUploadPhotoPathOnServer(photoFileName);

            if (File.Exists(pathOnServer))
            {
                try
                {
                    File.Delete(pathOnServer);
                }
                catch (Exception e)
                {
                    Log.Error(FoothillModule.Service, string.Format("Failed to delete uploaded photo '{0}'", pathOnServer), e);
                }              
            }

            pathOnServer = GetThumbnailPhotoPathOnServer(thumbnailFileName);
            if (File.Exists(pathOnServer))
            {
                try
                {
                    File.Delete(pathOnServer);
                }
                catch (Exception e)
                {
                    Log.Error(FoothillModule.Service, string.Format("Failed to delete uploaded thumbnail '{0}'", pathOnServer), e);
                }
            }
        }

        public string GetUploadPhotoImageUrl(string fileName)
        {
            return string.Format("{0}\\{1}", GlobalSettings.UploadPhotoFolder, fileName);
        }

        public string GetThumbnailPhotoImageUrl(string fileName)
        {
            return string.Format("{0}\\{1}", GlobalSettings.ThumbnailFolder, fileName);
        }

        public string GetUploadPhotoPathOnServer(string fileName)
        {
            return Path.Combine(Server.MapPath(GlobalSettings.UploadPhotoFolder), fileName);
        }

        public string GetThumbnailPhotoPathOnServer(string fileName)
        {
            return Path.Combine(Server.MapPath(GlobalSettings.ThumbnailFolder), fileName);
        }
    }
}
